package com.example.study

import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.navigation.findNavController
import androidx.navigation.ui.navigateUp
import com.example.study.databinding.ActivityDetailBinding
import com.example.study.page.Pages
import com.example.study.page.fragment.NavMainFragment

class DetailActivity : AppCompatActivity() {
    private lateinit var binding: ActivityDetailBinding

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityDetailBinding.inflate(layoutInflater)
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        val index = intent.getIntExtra("index", -1)
        if (index != -1) {
            val page = Pages.entries[index]
            supportFragmentManager.beginTransaction()
                .replace(R.id.detail, page.fragment())
                .addToBackStack(page.pageName()).commitAllowingStateLoss()
            binding.text.text = "详情：${page.pageName()}"
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        val navController = findNavController(R.id.nav_host_fragment_content_main)
        return super.onSupportNavigateUp()
                || NavMainFragment.configuration?.let { navController.navigateUp(it) } ?: false
    }

    private val callback = object :
        OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            this@DetailActivity.finish()
        }
    }

    override fun onStart() {
        super.onStart()
        this.onBackPressedDispatcher.addCallback(callback)
    }

    override fun onStop() {
        super.onStop()
        this.onBackPressedDispatcher.addCallback(callback)
    }

}